package servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

/*这个demo是用来显示访问时候显示cookie中上一次的时间*/
@WebServlet("/servletDemo03")
public class ServletDemo03 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Cookie[] cookies = req.getCookies();
        String value=null;
        for (Cookie cookie:cookies) {
            String name = cookie.getName();
            if ("date".equals(name)){
                value = cookie.getValue();
            }
        }
//        获取当前访问时间
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd-HH:mm:ss");
        Date date = new Date();
        String format = sdf.format(date);
//      获取当前访问时间放在cookie中
        Cookie c = new Cookie("date",format );
//        把当前cookie发送出去
        resp.addCookie(c);
//        处理乱码
                resp.setContentType("text/html;charset=utf-8");
         if(value==null){
             resp.getWriter().write("这是第一次访问");
         }else{
             resp.getWriter().write("这是上一次访问时间为:"+value);
         }


    }

}



